package com.sparrow.core;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.sparrow.constant.CACHE_KEY;

/**
 * 系统缓存类
 * 
 * 加泛型为上层调用时不用类型转换
 * 
 * @author zhanglizhi
 * @date Aug 2, 2011 8:37:06 PM
 * @version 1.0
 */
public class Cache {
	private Map<String, Map<String, ?>> map = new ConcurrentHashMap<String, Map<String, ?>>();
	private static Cache cache = new Cache();

	public static Cache getInstance() {
		return cache;
	}

	/**
	 * 获取map中的值
	 * 
	 * @author zhanglizhi
	 * @date Aug 2, 2011
	 * @version 1.0
	 * @param key
	 * @return
	 */
	private <T> T get(Map<String, T> map, String key) {
		if (map.containsKey(key)) {
			T value = map.get(key);
			if (value == null) {
				map.remove(key);
				return null;
			} else {
				return value;
			}
		} else {
			return null;
		}
	}

	/**
	 * 从二级缓存中获取值 不过期
	 * 
	 * @author zhanglizhi
	 * @date Jun 14, 2011
	 * @version 1.0
	 * @param key
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T> T get(String childCacheKey, String key) {
		Map<String, ?> childCache = this.get(this.map, childCacheKey);
		if (childCache == null) {
			return null;
		} else {
			return (T) this.get(childCache, key);
		}
	}

	/**
	 * 从二级默认缓存中获取
	 * 
	 * @author zhanglizhi
	 * @date Aug 2, 2011
	 * @version 1.0
	 * @param key
	 * @return
	 */
	public <T> T getValueFromDefaultCache(String key) {
		return this.get(CACHE_KEY.DEFAULT, key);
	}

	/**
	 * 存入一级缓存
	 * 
	 * 只接收Map
	 * 
	 * 业务上只接受不变的数据
	 * 
	 * @author zhanglizhi
	 * @date 2013-4-4
	 * @version 1.0
	 * @param key
	 * @param value
	 */
	public <T> void put(String key, Map<String, T> value) {
		this.map.put(key, value);
	}

	/**
	 * 存入二级缓存 不过期直接保存缓存值
	 * 
	 * @author zhanglizhi
	 * @date Aug 2, 2011
	 * @version 1.0
	 * @param childCacheKey
	 * @param key
	 * @param value
	 */
	public <T> void put(String childCacheKey, String key, T value) {
		@SuppressWarnings("unchecked")
		Map<String, T> childCache = (Map<String, T>) this.get(this.map,
				childCacheKey);
		if (childCache == null) {
			childCache = new ConcurrentHashMap<String, T>();
			this.map.put(childCacheKey, childCache);
		}
		childCache.put(key, value);
	}

	/**
	 * 存入二级默认缓存 不过期直接保存缓存值
	 * 
	 * @author zhanglizhi
	 * @date Aug 2, 2011
	 * @version 1.0
	 * @param key
	 * @param value
	 */
	public <T> void putToDefaultCache(String key, T value) {
		this.put(CACHE_KEY.DEFAULT, key, value);
	}

	@SuppressWarnings("unchecked")
	public <T> Map<String, T> get(String key) {
		return (Map<String, T>) cache.get(this.map, key);
	}
}
